import sys
import os
from PyQt5.QtWidgets import QApplication, QWidget, QMessageBox
from PyQt5.QtCore import pyqtSlot, pyqtSignal
import pandas as pd
import akshare as ak
from typing import Callable

from pts.task_engine import TaskEngine, Task
from pts.constant import TaskType
from .Ui_market_fund import Ui_MarketFund
from ..global_functions import displayDataFrame
from ..setting import SETTINGS
from ..web_crawler import stock_market_fund_flow_1


class MarketFund(QWidget, Ui_MarketFund):
    """2-大盘资金流 页面"""
    # 大盘资金流的文件名
    file_hsls = r'Data\dpzj_hsls.csv'
    file_hs = r'Data\dpzj_hs.csv'
    file_ss = r'Data\dpzj_ss.csv'
    file_cyb = r'Data\dpzj_cyb.csv'

    # 用于处理自动刷新完成信息的信号
    signal: pyqtSignal = pyqtSignal(str)

    def __init__(self, task_engine: TaskEngine, displayStatusMess: Callable):
        """初始化"""
        super(MarketFund, self).__init__()
        self.setupUi(self)

        # 从主窗口接受到的任务引擎
        self.task_engine: TaskEngine = task_engine
        # 主窗口的信息显示函数
        self.displayStatusMess: Callable = displayStatusMess

        self.initUi()
        # 初始化与本页面相关的任务
        self.initTask()

    def initTask(self):
        """初始化与本页面相关的任务"""
        # 盘后任务
        task = Task(TaskType.ph, self.process_task, self.signal.emit, task_id=2)
        self.task_engine.put(task)

        # 为信号关联槽函数
        self.signal.connect(self.display_task)

    def process_task(self) -> str:
        """
        任务的执行函数，供任务引擎的守护线程调用
        :return: 任务执行的结果信息
        """
        return self.reloadAll(True)

    def display_task(self, mess: str):
        """
        任务执行结果的显示函数，供任务引擎的守护线程调用
        :param mess: 任务执行的结果信息
        :return: 无
        """
        # 在主窗口的状态栏上显示结果信息
        self.displayStatusMess(mess)
        # 更新页面上的列表
        self.displayAll()

    def initUi(self):
        '''初始化界面'''
        self.displayAll()

        self.tabWidget.setCurrentIndex(SETTINGS["CurrentIndex3"])

    def reloadAll(self, reload: bool) -> str:
        s = "下载大盘资金流数据成功。"

        if not os.path.exists(self.file_hsls) or reload:
            try:
                stock_data = ak.stock_market_fund_flow()
                stock_data = stock_data.iloc[::-1]
                stock_data.to_csv(self.file_hsls, index=False)
            except BaseException as ex:
                s = '下载沪深两市大盘资金流失败，可稍后重新尝试：\n{}。'.format(ex.args)

        if not os.path.exists(self.file_hs) or reload:
            try:
                stock_data = stock_market_fund_flow_1(market="沪市")
                stock_data.to_csv(self.file_hs, index=False)
            except BaseException as ex:
                s = '下载沪市大盘资金流失败，可稍后重新尝试：\n{}。'.format(ex.args)

        if not os.path.exists(self.file_ss) or reload:
            try:
                stock_data = stock_market_fund_flow_1(market="深市")
                stock_data.to_csv(self.file_ss, index=False)
            except BaseException as ex:
                s = '下载深市大盘资金流失败，可稍后重新尝试：\n{}。'.format(ex.args)

        if not os.path.exists(self.file_cyb) or reload:
            try:
                stock_data = stock_market_fund_flow_1(market="创业板")
                stock_data.to_csv(self.file_cyb, index=False)
            except BaseException as ex:
                s = '下载创业板大盘资金流失败，可稍后重新尝试：\n{}。'.format(ex.args)

        return s

    def displayAll(self):
        s = self.reloadAll(False)
        if s != "下载大盘资金流数据成功。":
            QMessageBox.information(self, '提示信息', s)

        stock_data = pd.read_csv(self.file_hsls)
        displayDataFrame(stock_data, self.twHSLS, amountList=[5, 7, 9, 11, 13], startCol=0, orderCol=[5, ])

        stock_data = pd.read_csv(self.file_hs)
        displayDataFrame(stock_data, self.twHS, amountList=[3, 5, 7, 9, 11], startCol=0, bkKind=2, orderCol=[3, ])

        stock_data = pd.read_csv(self.file_ss)
        displayDataFrame(stock_data, self.twSS, amountList=[3, 5, 7, 9, 11], startCol=0, bkKind=2, orderCol=[3, ])

        stock_data = pd.read_csv(self.file_cyb)
        displayDataFrame(stock_data, self.twCYB, amountList=[3, 5, 7, 9, 11], startCol=0, bkKind=2, orderCol=[3, ])

    @pyqtSlot()
    def on_btnRefresh_clicked(self):
        s = self.reloadAll(True)
        QMessageBox.information(self, '提示信息', s)

        self.displayAll()

if __name__ == '__main__':
    app = QApplication(sys.argv)
    ui = MarketFund()
    ui.show()
    sys.exit(app.exec_())
